package server;

import common.Contact;

import java.io.IOException;
import java.util.List;

public class Model {
    private final DataAccess dataAccess;

    public Model() {
        this.dataAccess = new DataAccess();
    }

    public List<Contact> getContacts() throws IOException {
        return dataAccess.readContacts();
    }

    public void addContact(Contact contact) throws IOException {
        List<Contact> contacts = dataAccess.readContacts();
        contacts.add(contact);
        dataAccess.writeContacts(contacts);
    }

    public void deleteContact(String name) throws IOException {
        List<Contact> contacts = dataAccess.readContacts();
        contacts.removeIf(contact -> contact.getName().equals(name));
        dataAccess.writeContacts(contacts);
    }

    public void updateContact(String name, String newPhone) throws IOException {
        List<Contact> contacts = dataAccess.readContacts();
        for (Contact contact : contacts) {
            if (contact.getName().equals(name)) {
                contact = new Contact(name, newPhone); // Update the contact
            }
        }
        dataAccess.writeContacts(contacts);
    }
}
